package com.rdiot.yx485.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.drake.tooltip.dialog.BubbleDialog
import com.github.gzuliyujiang.wheelpicker.widget.OptionWheelLayout
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.FraMineBinding
import com.rdiot.yx485.net.getAllFamilyData
import com.rdiot.yx485.net.getFamilyData
import com.rdiot.yx485.net.setDefaultFamily
import com.rdiot.yx485.ui.family.FamilyManagementActivity
import com.rdiot.yx485.ui.web.WebActivity
import com.rdiot.yx485.util.*
import kotlinx.coroutines.delay


/**
 * 我的
 * @author mR2hao
 * @date 2022/11/9
 */
class MineFragment : BaseFragment<FraMineBinding>() {
    override fun getLayoutId() = R.layout.fra_mine

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        LocalData.userData.observe(this) { userData ->
            binding.userData = userData
            val imgUrl = "${LocalData.apiHost.avatarHost}${userData?.photo}"
            binding.ivAvatar.circleImg(imgUrl)
        }

        LocalData.familyData.observe(this) { familyData ->
            binding.familyData = familyData
        }
        binding.llHome.setClickLimitListener(clickLimitListener)
        binding.llHomeManagement.setClickLimitListener(clickLimitListener)
        binding.llSetting.setClickLimitListener(clickLimitListener)
        binding.llUserInfo.setClickLimitListener(clickLimitListener)
        binding.llHelp.setClickLimitListener(clickLimitListener)
        binding.tvSa.setClickLimitListener(clickLimitListener)
        binding.tvPp.setClickLimitListener(clickLimitListener)


        //测试用 令Token失效
//        if (BuildConfig.DEBUG) {
//            binding.nb.setLeftClickListener {
//                LocalData.makeTokenErr = true
//            }
//        }

    }

    override fun onResume() {
        super.onResume()
        scopeNetLife {
            getAllFamilyData(false).await().apply {
                LocalData.allFamily.postValue(this.toMutableList())
            }
        }
    }

    private val clickLimitListener = object : ClickLimitListener {
        override fun onClickLimit(view: View) {
            when (view) {
                binding.llHome -> {
                    showFamilyPicker()
                }

                binding.llHomeManagement -> {
                    act.clearGoTo(FamilyManagementActivity::class.java)
                }
                // 用户信息
                binding.llUserInfo -> {
                    act.clearGoTo(UserInfoActivity::class.java)
                }

                binding.llHelp -> {
                    act.clearGoTo(
                        WebActivity.getNewWebIntent(
                            act,
                            "https://app.yongxulvjian.com/#/HelpList",
                            "帮助列表"
                        )
                    )
                }
                binding.llSetting->{
                    act.clearGoTo(SettingActivity::class.java)
                }

                binding.tvSa -> {
                    act.clearGoTo(
                        WebActivity.getNewWebIntent(
                            act,
                            "https://app.yongxulvjian.com/#/ServiceAgreement",
                            "用户协议"
                        )
                    )
                }

                binding.tvPp -> {
                    act.clearGoTo(
                        WebActivity.getNewWebIntent(
                            act,
                            "https://app.yongxulvjian.com/#/PrivacyPolicy",
                            "隐私政策"
                        )
                    )
                }
            }
        }
    }

    private fun showFamilyPicker() {
        var isSetDefault = false

        val nameList = mutableListOf<String>()
        LocalData.allFamily.value?.forEach {
            nameList.add(it.name)
        }
        var optionWheelLayout: OptionWheelLayout? = null

        IAlertDialog
            .build(this)
            .setTitle(R.string.change_family)
            .setContentView(R.layout.dialog_sel_family)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setNegClickListener { dialogInterface ->
                dialogInterface.dismiss()

            }
            .setPosClickListener { dialogInterface ->
                val p = optionWheelLayout?.wheelView?.currentPosition ?: 0
                val newSelFamilyData = LocalData.allFamily.value?.get(p)
                val bubbleDialog = BubbleDialog(requireActivity(), getString(R.string.changing))

                scopeDialog(cancelable = BuildConfig.DEBUG, dialog = bubbleDialog) {
                    LocalData.selFamilyId.postValue(newSelFamilyData?.recordId)
                    val getFamily = getFamilyData(newSelFamilyData?.recordId)
                    getFamily.await().also {
                        LocalData.familyData.postValue(it)
                    }

                    if (isSetDefault) {
                        val setFamily = setDefaultFamily(newSelFamilyData?.recordId)
                        setFamily.await()
                    }

                    delay(1000)
                    dialogInterface.dismiss()
                }

            }
            .setDismissible(false)
            .setAlpha(1.0F)
            .setPosButtonTextColor(resources.getColor(R.color.btn_blue, null))
            .setOnViewHandler { holder, _ ->
                optionWheelLayout = holder.getView(R.id.wheel_option)
                optionWheelLayout?.labelView?.textSize = 16.0f
                optionWheelLayout?.labelView?.setTextColor(act.getColor(R.color.login_btn_color))
                optionWheelLayout?.setData(nameList)
                optionWheelLayout?.setDefaultValue(LocalData.familyData.value?.name)
                holder.getView<LinearLayout>(R.id.ll_set_default).setClickAlpha {
                    isSetDefault = !isSetDefault

                    holder.getView<AppCompatImageView>(R.id.iv_check_box).setImageResource(
                        if (isSetDefault) {
                            R.mipmap.icon_check_sel
                        } else {
                            R.mipmap.icon_check
                        }
                    )

                }

            }.show()
    }
}